<template>
  <a-modal
    v-model:open="visible"
    title="百度地图"
    width="90%"
    :footer="null"
    @cancel="handleCancel"
    destroyOnClose
  >
    <div style="display: flex; height: 500px">
      <!-- 左侧面板 -->
      <div style="width: 300px; border-right: 1px solid #d9d9d9; padding: 16px; overflow-y: auto">
        <div style="margin-bottom: 16px">
          <a-button
            :type="isEditing ? 'primary' : 'default'"
            @click="toggleEditMode"
            style="width: 100%"
          >
            {{ isEditing ? '退出编辑' : '开始编辑' }}
          </a-button>
        </div>

        <div v-if="markers.length > 0">
          <h4>标记点列表</h4>
          <div
            v-for="marker in markers"
            :key="marker.id"
            style="margin-bottom: 8px; padding: 8px; border: 1px solid #f0f0f0; border-radius: 4px"
          >
            <div>
              <strong>标记 {{ marker.number }}</strong>
            </div>
            <div>经度: {{ marker.lng.toFixed(6) }}</div>
            <div>纬度: {{ marker.lat.toFixed(6) }}</div>
            <a-button size="small" danger @click="removeMarker(marker.id)" style="margin-top: 4px">
              删除
            </a-button>
          </div>
          <a-button @click="clearAllMarkers" danger style="width: 100%; margin-top: 8px">
            清空所有标记
          </a-button>
        </div>

        <div v-else style="color: #999; text-align: center; margin-top: 50px">
          点击"开始编辑"后，在地图上点击可添加标记点
        </div>
      </div>

      <!-- 地图容器 -->
      <div style="flex: 1; position: relative">
        <!-- 编辑模式提示 -->
        <div
          v-if="isEditing"
          style="
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1000;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
          "
        >
          编辑模式：点击地图添加标记点
        </div>
        <div id="baidu-map-container" style="width: 100%; height: 100%"></div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { watch, nextTick, ref } from 'vue'

const visible = defineModel<boolean>('open', { default: false })
let map: any = null

// 编辑状态
const isEditing = ref(false)
const markers = ref<
  Array<{
    id: number
    number: number
    lng: number
    lat: number
    marker: any
  }>
>([])
let markerCounter = 0

// 监听visible变化
watch(visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initMap()
    })
  } else {
    // 关闭弹窗时重置状态
    isEditing.value = false
    clearAllMarkers()
  }
})

const handleCancel = () => {
  visible.value = false
}

// 切换编辑模式
const toggleEditMode = () => {
  isEditing.value = !isEditing.value
  if (map) {
    if (isEditing.value) {
      // 开启编辑模式，添加点击事件
      map.addEventListener('click', handleMapClick)
      map.setDefaultCursor('crosshair')
    } else {
      // 关闭编辑模式，移除点击事件
      map.removeEventListener('click', handleMapClick)
      map.setDefaultCursor('default')
    }
  }
}

import markerIcon from './images/markIcon.png'

// 地图点击事件
const handleMapClick = (e: any) => {
  if (!isEditing.value) return

  const point = new BMapGL.Point(e.latlng.lng, e.latlng.lat)
  markerCounter++
  console.log(e)

  // 创建标记
  const icon = new BMapGL.Icon(markerIcon, new BMapGL.Size(44, 72))
  const marker = new BMapGL.Marker(point,{icon,offset: new BMapGL.Size(0, -25),})
  // 创建标签（显示数字）
  const label = new BMapGL.Label(markerCounter.toString(), {
    offset: new BMapGL.Size(-22, -50),
    
  })
  label.setStyle({
    color: 'white',
    backgroundColor: 'transparent',
    border: 'none',
    width: '44px',
    height: '20px',
    lineHeight: '20px',
    textAlign: 'center',
    fontSize: '18px',
    fontWeight: 'bold',
  })
  marker.setLabel(label)

  // 添加到地图
  map.addOverlay(marker)

  // 保存标记信息
  const markerInfo = {
    id: Date.now() + Math.random(),
    number: markerCounter,
    lng: point.lng,
    lat: point.lat,
    marker: marker,
  }
  markers.value.push(markerInfo)
}

// 删除单个标记
const removeMarker = (id: number) => {
  const index = markers.value.findIndex((m) => m.id === id)
  if (index !== -1) {
    const markerInfo = markers.value[index]
    map.removeOverlay(markerInfo.marker)
    markers.value.splice(index, 1)
  }
}

// 清空所有标记
const clearAllMarkers = () => {
  markers.value.forEach((markerInfo) => {
    map.removeOverlay(markerInfo.marker)
  })
  markers.value = []
  markerCounter = 0
}

// 初始化百度地图
const initMap = () => {
  // 如果地图已存在，则销毁重新创建
  if (map) {
    map.destroy()
    map = null
  }

  // 确保百度地图API已加载
  if (typeof window.BMapGL !== 'undefined') {
    createMap()
  } else {
    loadBaiduMapScript()
  }
}

// 加载百度地图脚本
const loadBaiduMapScript = () => {
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src =
    'https://api.map.baidu.com/api?v=3.0&ak=GAp7ANvstQXFo9sBF4TO772lvNPzz7ib&type=webgl&callback=initBaiduMap'
  document.head.appendChild(script)

  // 设置全局回调函数
  window.initBaiduMap = () => {
    createMap()
  }
}

// 创建地图实例
const createMap = () => {
  const mapContainer = document.getElementById('baidu-map-container')
  if (!mapContainer) return

  // 创建地图实例
  map = new BMapGL.Map('baidu-map-container')

  // 设置中心点坐标和地图级别
  const point = new BMapGL.Point(116.404, 39.915) // 北京坐标
  map.centerAndZoom(point, 12)

  // 开启鼠标滚轮缩放
  map.enableScrollWheelZoom(true)

  // 添加缩放控件
  map.addControl(new BMapGL.ZoomControl())

  // 添加比例尺控件
  map.addControl(new BMapGL.ScaleControl())
}
</script>

<style lang="scss" scoped>
#baidu-map-container {
  border-radius: 4px;
  overflow: hidden;
}
</style>
